package com.imooc.girl.service;

import com.imooc.girl.domain.GetStuInfoForm;
import com.imooc.girl.domain.ReturnResult;
import com.imooc.girl.repository.InsInfoRepositry;
import com.imooc.girl.repository.Stu_infoRepository;
import com.imooc.girl.util.MapStuInfo;
import com.imooc.girl.util.ReturnResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class StuInfoService {
    @Autowired
    private Stu_infoRepository stu_infoRepository;
    @Autowired
    private InsInfoRepositry insInfoRepositry;

    public ReturnResult getStuInfoServe(GetStuInfoForm getStuInfoForm) throws Exception{
        if(getStuInfoForm.getNumber()==null && getStuInfoForm.getInstructorID()==null){
            throw new Exception("number和instructorID必须存在一个");
        }else if(getStuInfoForm.getCurrentPage()==null){
            throw new Exception("当前页必须存在");
        }else if(getStuInfoForm.getPageSize().intValue()<=0){
            throw new Exception("页面大小必须大于0");
        }else {
            ReturnResult result;
            String grade=insInfoRepositry.findOneById(getStuInfoForm.getInstructorID());
            Map<Object, Object> cur = new HashMap<>();
            if (getStuInfoForm.getNumber() == null) {
                Pageable pageable = PageRequest.of(getStuInfoForm.getCurrentPage().intValue(), getStuInfoForm.getPageSize().intValue(), Sort.Direction.ASC, "StuId");
                Page<Object[]> res=stu_infoRepository.findByStuClass(grade, pageable);
                List<Object[]> curr = res.getContent();
                MapStuInfo.getMapSruInfo(curr, cur);
                cur.put("recordQuantity", res.getTotalElements());
            } else {
                cur.put("recordQuantity", 1);
                MapStuInfo.getMapSruInfo(stu_infoRepository.findOneById(getStuInfoForm.getNumber()), cur);
            }
            result = ReturnResultUtil.getSuccess(cur,"成功");
            return result;
        }
    }
}
